﻿using System;
using System.Collections.Generic;

using FineUI;

using EDP.Common;
using EDP.Common.Model;
using EDP.Framework.Form;
using EDP.Organization;

using School.Model;
using School.Business;
using School.Model.Organization;

namespace EDP.WebForm.school.student
{
    public partial class _default : WebFormBase
    {
        private readonly StudentBLL bll_Student = StudentBLL.Create(); //创建StudentBLL类实例,通过Create方法创建可实现自动化日志
        private readonly string m_eidtUrl = Config.Application.ApplictionFullPath + "edp.webform/school/student/edit.aspx?itemId={0}&orgId={1}";

        protected void Page_Load(object sender, EventArgs e) {
            this.grid_List.PageSizeChange += this.gridPageSizeChange; //列表控件注册每页记录数改变的方法,通常情况是调用绑定列表的方法,当每页记录数改变的时候重新绑定列表
            if (!this.IsPostBack) {
                this.createTree();
                this.bindGrid();
            }
        }

        #region **----grid控件---------------------------**
        private void gridPageSizeChange(object sender, EventArgs e) {
            this.bindGrid();
        }

        /// <summary>
        /// 绑定列表
        /// </summary>
        private void bindGrid() {
            StudentQueryModel queryModel = new StudentQueryModel();

            //设置查询对象值,根据控件QueryName的属性名称值设置,例如QueryName="NumberNameKeywrod",对应StudentQueryModel查询对象的NumberNameKeywrod属性
            //需要注意的是,查询工具栏的QueryToolbar属性值要设置为true
            this.SetQueryModel(queryModel);

            queryModel.ClassFullCode = this.hide_orgFullCode.Text;

            //******分页对象赋值--------------------------------------------------******
            queryModel.Page = new PageModel();
            queryModel.Page.PageSize = this.grid_List.PageSize;
            queryModel.Page.PageIndex = this.grid_List.PageIndex;
            queryModel.Page.SortName = this.grid_List.SortField;
            queryModel.Page.SortDirection = this.grid_List.SortDirection.ToLower();
            //******--------------------------------------------------------------******

            var result = this.bll_Student.GetStudentList(queryModel);
            if (result.ErrorCode == 0) {
                this.grid_List.DataSource = result.Content;
                this.grid_List.RecordCount = result.Page.RowCount;
                this.grid_List.DataBind();
            }
            else {
                string msg = result.Message.HasValue() ? result.Message : "获取学生列表异常";
                Alert.Show(msg, "学生管理", MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 列表分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grid_List_PageIndexChange(object sender, GridPageEventArgs e) {
            this.grid_List.PageIndex = e.NewPageIndex;
            this.bindGrid();
        }

        /// <summary>
        /// 列表排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grid_List_Sort(object sender, GridSortEventArgs e) {
            this.grid_List.SortField = e.SortField;
            this.grid_List.SortDirection = e.SortDirection;
            this.grid_List.PageIndex = 0;
            this.bindGrid();
        }

        /// <summary>
        /// 列表命令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grid_List_RowCommand(object sender, GridCommandEventArgs e) {
            string commandName = e.CommandName;
            var keys = this.grid_List.DataKeys[e.RowIndex];
            string itemId = keys[0].ToString();

            switch (commandName) {
                case "edit":
                    string url = string.Format(this.m_eidtUrl, itemId, this.hide_orgId.Text);
                    string script = this.win_edit.GetShowReference(this.BuildUrl(url), "修改学生信息", 700, 500);
                    //string script = this.win_edit.GetShowReference(this.BuildUrl(url), "修改学生信息", this.WindowWidth - 1000, this.WindowHeight - 600); //可通过减法来实现窗体大小自适应
                    PageContext.RegisterStartupScript(script);
                    break;
                case "delete":
                    var result = this.bll_Student.DeleteStudent(itemId);
                    if (result.Content)
                        this.bindGrid();
                    else {
                        if (result.Message.HasValue()) {
                            if (result.ErrorLevel == (int)ErrorLevelEnum.SystemError)
                                Alert.Show(result.Message, "删除学生", MessageBoxIcon.Error);
                            else
                                Alert.Show(result.Message, "删除学生", MessageBoxIcon.Warning);
                        }
                        else
                            Alert.Show("操作失败", "删除学生", MessageBoxIcon.Error);
                    }
                    break;
            }
        }
        #endregion

        #region **----树控件-----------------------------**
        private void createTree() {
            var list = this.bll_Student.GetOrganizationList().Content;
            if (list == null || !list.HasValue())
                return;

            var list_area = list.FindAll(t => t.PropertyId == 1 && t.Levels == 2); //校区

            var topList = list.FindAll(t => t.Levels == list[0].Levels); //顶级节点

            foreach (var item in topList) {
                TreeNode node = new TreeNode();
                node.NodeID = item.ID;
                node.Text = item.Name;
                node.CommandArgument = item.FullCode;
                node.EnableClickEvent = true;
                node.Expanded = true;
                if (item.PropertyId == (int)OrganizationUnitPropertyEnum.Organization)
                    node.Icon = Icon.Bricks;
                else if (item.PropertyId == (int)OrganizationUnitPropertyEnum.Department)
                    node.Icon = Icon.Package;

                //有校区则加载校区
                if (list_area != null && list_area.HasValue()) {
                    foreach (var area in list_area) {
                        TreeNode node_area = new TreeNode();
                        node_area.NodeID = area.ID;
                        node_area.Text = area.Name;
                        node_area.CommandArgument = area.FullCode;
                        node_area.EnableClickEvent = true;
                        node_area.Expanded = true;
                        if (area.PropertyId == (int)OrganizationUnitPropertyEnum.Organization)
                            node_area.Icon = Icon.Bricks;
                        else if (area.PropertyId == (int)OrganizationUnitPropertyEnum.Department)
                            node_area.Icon = Icon.Package;

                        this.addChildNode(list, node_area);
                        if (node_area.Nodes != null && node_area.Nodes.Count > 0)
                            node.Nodes.Add(node_area);
                    }
                }
                else
                    this.addChildNode(list, node);

                if ((node.Nodes != null && node.Nodes.Count > 0) || item.TypeNumbers == "004") //有子节点或班级节点则添加该节点
                    this.tree_org.Nodes.Add(node);
            }
        }

        private void addChildNode(List<OrganizationModel> itemList, TreeNode parentNode) {
            if (itemList == null || !itemList.HasValue())
                return;

            if (parentNode == null || parentNode.NodeID.IsEmpty())
                return;

            List<string> types = new List<string> { "001", "003", "004" }; //子节点只获取学校,年级,班级(使用的是组织类型编码)

            var list = itemList.FindAll(t => types.Contains(t.TypeNumbers) && t.ParentId == parentNode.NodeID);
            if (list == null || !list.HasValue()) {
                return;
            }

            foreach (var item in list) {
                TreeNode node = new TreeNode();
                node.NodeID = item.ID;
                node.Text = item.Name;
                node.CommandArgument = item.FullCode;
                node.EnableClickEvent = true;
                node.Expanded = item.PropertyId == (int)OrganizationUnitPropertyEnum.Organization ? true : false;
                node.Icon = Icon.Package;
                parentNode.Nodes.Add(node);

                this.addChildNode(itemList, node);
            }
        }

        protected void tree_org_NodeCommand(object sender, TreeCommandEventArgs e) {
            this.hide_orgFullCode.Text = e.CommandArgument;
            this.hide_orgId.Text = e.NodeID;
            this.bindGrid();
        }
        #endregion

        #region **----按钮事件---------------------------**
        /// <summary>
        /// 重写基类查询事件,实现查询方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void QueryClick(object sender, EventArgs e) {
            this.grid_List.PageIndex = 0;
            this.bindGrid();
        }

        protected void btn_user_add_Click(object sender, EventArgs e) {
            string url = string.Format(this.m_eidtUrl, string.Empty, this.tree_org.SelectedNodeID);
            string script = this.win_edit.GetShowReference(this.BuildUrl(url), "新增学生信息", 700, 500);
            PageContext.RegisterStartupScript(script);
        }
        #endregion

        protected void win_edit_Close(object sender, WindowCloseEventArgs e) {
            this.bindGrid();
        }
    }
}